//
//  HMComposePictureView.swift
//  MyWeibo
//
//  Created by apple on 16/4/26.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit
import SVProgressHUD

class HMComposePictureView: UICollectionView {
    
    //定义一个添加图片的闭包
    var selectedPictureClosure:(()->())?
    
    //当前picture显示的数据
    lazy var images:[UIImage] = []
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        super.init(frame: frame, collectionViewLayout: layout)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置ui
    func setupUI(){
        
        //设置背景颜色
        backgroundColor = UIColor.whiteColor()
        
        dataSource = self
        delegate = self
        
        //注册cell
        registerClass(HMComposePictureViewCell.self, forCellWithReuseIdentifier: "cell")
        
    }
    //设置控件布局
    override func layoutSubviews() {
        //设置控件布局
        super.layoutSubviews()
        
        //设置宽高大小
        let margin : CGFloat = 5
        let ItemW = (self.frame.width - 2 * margin) / 3
        
        //设置layout的itemsize 的大小
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: ItemW, height: ItemW)
        //设置行间距和列间距
        layout.minimumInteritemSpacing = margin
        layout.minimumLineSpacing = margin
        
    }
    //提供外界传入图片数据的方法
    func addImage(image:UIImage){
        //如果大于禁止添加
        if images.count < 9 {
            
            images.append(image)
            //刷新
            reloadData()
        }else{
            
            SVProgressHUD.showErrorWithStatus("图片已达上限")
        }
    }
    
}



// MARK: - collectionView代理方法的实现
extension HMComposePictureView:UICollectionViewDelegate,UICollectionViewDataSource{
    
    //数据源代理方法
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //设置初始默认为没有图片 自身隐藏
        self.hidden = images.count == 0
        
        print(images.count)
        
        //如果图片等于0或者9就不显示  其他显示原本数 + 1 个图片
        return images.count + ((images.count == 9 || images.count == 0 ) ? 0 : 1)
        
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        //创建cell
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! HMComposePictureViewCell
        
        //判断加载图片逻辑
        if indexPath.item == images.count {
            //如果是最后一张的话就加载自定义cell的加号图
            cell.image = nil
        }else{
            //正常显示图片
            cell.image = images[indexPath.item]
        }
        //定义闭包方法
        cell.deleteButtonClosoure = {[weak self] in
            //删除相应的图片
            self?.images.removeAtIndex(indexPath.item)
            //刷新
            self?.reloadData()
        }
        
        return cell
    }
    
    //监听cell的点击
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        //代表最后一个被点击了  调用闭包通知添加图片
        if indexPath.item == images.count{
            
            selectedPictureClosure?()
        }
        
    }
    
}

class HMComposePictureViewCell: UICollectionViewCell {
    
    //点击删除按钮要执行的闭包
    var deleteButtonClosoure:(()->())?
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置添加图片cell的逻辑 如果为空 图片加载为添加图片
    var image:UIImage?{
        
        didSet{
            
            if image == nil{
                
                imageView.image = UIImage(named: "compose_pic_add")
                
                //隐藏删除按钮
                deleteButton.hidden = true
                
            }else{
                
                deleteButton.hidden = false
                imageView.image = image
            }
        }
        
    }
    
    func setupUI(){
        //添加控件
        contentView.addSubview(imageView)
        contentView.addSubview(deleteButton)
        
        
        //设置空间约束大小
        imageView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(contentView)
        }
        //删除按钮约束
        deleteButton.snp_makeConstraints { (make) -> Void in
            
            make.top.trailing.equalTo(imageView)
            
        }
    }
    
    //删除按钮的点击方法
    @objc private func deleteButtonClick(){
        
        //执行闭包删除相对应的图片
        deleteButtonClosoure?()
        
    }
    
    
    //懒加载imageview
    private lazy var imageView:UIImageView = UIImageView()
    
    //懒加载删除按钮
    private lazy var deleteButton:UIButton = {
        
        let button = UIButton()
        
        //设置图片
        button.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        //添加点击方法
        button.addTarget(self, action: "deleteButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()
    
    
}